<?php

namespace app\api\controller;

use Throwable;
use think\Response;
use app\common\library\Upload;
use app\common\controller\Frontend;
use app\common\controller\Api;

class Dida extends Frontend
{
  protected array $noNeedLogin = ['callbake', 'createTask', 'isWarn', 'sendTask', 'getTemperature', 'getTemperature'];

  protected array $noNeedPermission = ['callbake', 'createTask'];

  public function initialize(): void
  {
    parent::initialize();
  }
  /**
   * 滴答清单回调
   * @param string $code
   * @param string $state
   * @return void
   */
  public function callbake($code, $state): void
  {
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_URL => "https://dida365.com/oauth/token",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "client_id=j5B9M6Fy0PmxS8MYeY&client_secret=*!c%40i%23(QHJ537%23w25oLTZi%264IFAzOIFu&code=" . $code . "&grant_type=authorization_code&scope=tasks%3Awrite&redirect_uri=https%3A%2F%2Fnewcmt.chemeite.com.cn%2Fapi%2FDida%2Fcallbake%26server%3D1",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Connection: keep-alive",
        "Cookie: AWSALB=rARD1nL%2BUHtVTsrVDayQ1oL9CTmiFB2%2FT4DWBqovwMEpWJErCUzsNqhcXIoMQ5m7DGSdiIORDDyWtem01%2FStYNndMJQZHmV9h3xYtmvaVqD0YYOpXXmoWirZbT7j;AWSALBCORS=rARD1nL%2BUHtVTsrVDayQ1oL9CTmiFB2%2FT4DWBqovwMEpWJErCUzsNqhcXIoMQ5m7DGSdiIORDDyWtem01%2FStYNndMJQZHmV9h3xYtmvaVqD0YYOpXXmoWirZbT7j",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
      CURLOPT_SSL_VERIFYPEER => false,  // 不验证对等证书
      CURLOPT_SSL_VERIFYHOST => false   // 不验证主机名
    ]);
    $response = curl_exec($curl);
    $err = curl_error($curl);
    curl_close($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      $response = json_decode($response, true);
      if (isset($response['access_token'])) {
        # 如果获取成功则添加记录
        $this->model = new \app\admin\model\didauser\Info();
        $access_token = $response['access_token'];
        $expires_in = $response['expires_in'];
        #取当前10位数时间戳
        $time = time();
        $datetime = date('Y-m-d H:i:s', $expires_in + $time);
        # 判断账号是否存在如果存在则账号则更新token
        var_dump($response);
        $res = $this->model->where('state', '=', $state)->find();
        var_dump($res);
        if ($res) {
          $res['token'] = $access_token;
          $res['datetime'] = $datetime;
          $res['update_time'] = $time;
          $res->save();
        } else {
          $data = [
            'token' => $access_token,
            'datetime' => $datetime,
            'state' => $state
          ];
          $this->model->save($data);
        }
      } else {
        $this->error("获取失败！");
      }
    }
  }
  /**
   * 创建任务
   * @return void
   */
  public function createTask(): void
  {
    if ($this->isWarn()) {
      // $this->model = new \app\admin\model\User();
      // // 获取每一个用户最新的token
      // $user = $this->model->alias('a')
      //   ->join('ba_didauser_info b', 'a.id = b.state')
      //   ->field('max(b.token) as token,b.state,a.username')
      //   ->order('b.id', 'desc')
      //   ->group('a.id')
      //   ->select();
      // //循环输出
      $this->model = new \app\admin\model\didauser\Info();
      $user = $this->model->select();
      $time = time();
      foreach ($user as $key => $value) {
        $timestamp = strtotime($value['timestamp']);
        if (($time - $timestamp) / 60 >= 10) {
          //距离上次预警时间大于10分钟，可以再次预警。
          $this->sendTask($value);
          $value['timestamp'] = $time;
          $value->save();
        } else {
          echo "距离上次预警时间小于10分钟，不能再次预警。";
        }
      }
      // $this->ModifyWarningStatus();
      // sleep(5);
    }
  }

  /**
   * 发送任务信息
   * @return void
   */
  public function sendTask($User): void
  {
    $dateTime = new \DateTime();
    $dateTime->modify('+120 seconds');
    $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
    $formattedDateTime = $dateTime->format('Y-m-d\TH:i:s') . $dateTime->format('O');
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_URL => "https://dida365.com/open/v1/task",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "{\r\n  \"title\": \"温度传感器告警信息\",\r\n  \"content\": \"温度传感器告警信息\",\r\n  \"desc\": \"温度传感器告警信息\",\r\n  \"isAllDay\": false,\r\n  \"startDate\": \"" . $formattedDateTime . "\",\r\n  \"dueDate\": \"" . $formattedDateTime . "\",\r\n  \"timeZone\": \"Asia/Shanghai\",\r\n  \"reminders\": [ \"TRIGGER:PT0S\" ],\r\n  \"repeatFlag\": \"\",\r\n  \"priority\": 5,\r\n  \"sortOrder\": 1\r\n}",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Authorization: Bearer " . $User["token"],
        "Connection: keep-alive",
        "Content-Type: application/json",
        "Cookie: AWSALB=XySsb%2B%2Bw6Z4dXxoEttRqrgQOtxtxKBn8iRJTmN%2FX8JkasuDTZgbIOvK2Dm1palIKx6uDQjWlDvzWHQIPes8xm323Z9rFVFDBi4Haq2G1gKFbStzwMY1zt0ztbnyF;AWSALBCORS=XySsb%2B%2Bw6Z4dXxoEttRqrgQOtxtxKBn8iRJTmN%2FX8JkasuDTZgbIOvK2Dm1palIKx6uDQjWlDvzWHQIPes8xm323Z9rFVFDBi4Haq2G1gKFbStzwMY1zt0ztbnyF",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
      CURLOPT_SSL_VERIFYPEER => false,  // 不验证对等证书
      CURLOPT_SSL_VERIFYHOST => false   // 不验证主机名
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }
  }
  /**
   * 当前是否需要预警
   * @return bool
   */
  public function isWarn(): bool
  {
    $Temperature = $this->getTemperature();
    $Threshold = $this->getThreshold();
    // $HasThereBeenARecentWarning = $this->HasThereBeenARecentWarning();
    $WarningSwitchStatus = $this->WarningSwitchStatus();
    if ($Temperature != 'unavailable' && $Threshold != 'unavailable' && $WarningSwitchStatus == true) {
      if ($Temperature < $Threshold) {
        return true;
      }
    }
    return false;
  }
  /**
   * 获取阈值
   * @return string
   */
  public function getThreshold(): string
  {
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_PORT => "8123",
      CURLOPT_URL => "http://150.158.35.140:8123/api/states/input_number.di_wen_bao_jing_yu_zhi",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_POSTFIELDS => "",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMDNmMWJjZDg4OTc0MzEwYmIwOWNmY2I1MWRmM2ZiYyIsImlhdCI6MTczNTQ2MDk2OCwiZXhwIjoyMDUwODIwOTY4fQ.KSUcREAdRSVkDf5yUMsnHPKF_ovQS9921A722YYO3VQ",
        "Connection: keep-alive",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
      return 'unavailable';
    } else {
      $response = json_decode($response, true);
      return $response['state'];
    }
  }
  /**
   * 获取温度
   * @return string
   */
  public function getTemperature(): string
  {
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_PORT => "8123",
      CURLOPT_URL => "http://150.158.35.140:8123/api/states/sensor.sonoff_10022f634a_temperature",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_POSTFIELDS => "",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMDNmMWJjZDg4OTc0MzEwYmIwOWNmY2I1MWRmM2ZiYyIsImlhdCI6MTczNTQ2MDk2OCwiZXhwIjoyMDUwODIwOTY4fQ.KSUcREAdRSVkDf5yUMsnHPKF_ovQS9921A722YYO3VQ",
        "Connection: keep-alive",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
      return 'unavailable';
    } else {
      $response = json_decode($response, true);
      return $response['state'];
    }
  }
  /**
   * 获取温度api
   * @return void
   */
  public function getTemperatureapi(): void
  {
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_PORT => "8123",
      CURLOPT_URL => "http://150.158.35.140:8123/api/states/sensor.sonoff_10022f634a_temperature",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_POSTFIELDS => "",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMDNmMWJjZDg4OTc0MzEwYmIwOWNmY2I1MWRmM2ZiYyIsImlhdCI6MTczNTQ2MDk2OCwiZXhwIjoyMDUwODIwOTY4fQ.KSUcREAdRSVkDf5yUMsnHPKF_ovQS9921A722YYO3VQ",
        "Connection: keep-alive",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
      $res =  'unavailable';
    } else {
      $response = json_decode($response, true);
      $res =  $response['state'];
    }
    $this->success('', $res);
  }
  /**
   * 近期是否预警
   * @return string
   */
  public function HasThereBeenARecentWarning(): string
  {
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_PORT => "8123",
      CURLOPT_URL => "http://150.158.35.140:8123/api/states/input_boolean.jin_qi_shi_fou_yu_jing_yu_jing",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_POSTFIELDS => "",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMDNmMWJjZDg4OTc0MzEwYmIwOWNmY2I1MWRmM2ZiYyIsImlhdCI6MTczNTQ2MDk2OCwiZXhwIjoyMDUwODIwOTY4fQ.KSUcREAdRSVkDf5yUMsnHPKF_ovQS9921A722YYO3VQ",
        "Connection: keep-alive",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
      return false;
    } else {
      $response = json_decode($response, true);
      if ($response['state'] == 'on') {
        return true;
      } else {
        return false;
      }
    }
  }
  /**
   * 预警开关状态
   * @return string
   */
  public function WarningSwitchStatus(): string
  {
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_PORT => "8123",
      CURLOPT_URL => "http://150.158.35.140:8123/api/states/input_boolean.wen_du_yu_jing_kai_guan",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_POSTFIELDS => "",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMDNmMWJjZDg4OTc0MzEwYmIwOWNmY2I1MWRmM2ZiYyIsImlhdCI6MTczNTQ2MDk2OCwiZXhwIjoyMDUwODIwOTY4fQ.KSUcREAdRSVkDf5yUMsnHPKF_ovQS9921A722YYO3VQ",
        "Connection: keep-alive",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);
    if ($err) {
      echo "cURL Error #:" . $err;
      return false;
    } else {
      $response = json_decode($response, true);
      if ($response['state'] == 'on') {
        return true;
      } else {
        return false;
      }
    }
  }
  /**
   * 修改预警状态
   * @return void
   */
  public function ModifyWarningStatus(): void
  {

    $curl = curl_init();

    curl_setopt_array($curl, [
      CURLOPT_PORT => "8123",
      CURLOPT_URL => "http://150.158.35.140:8123/api/states/input_boolean.jin_qi_shi_fou_yu_jing_yu_jing",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => "{\r\n    \"state\": \"off\",\r\n\t\"attributes\": {\r\n\t\t\"editable\": true,\r\n\t\t\"icon\": \"mdi:alarm-light-off\",\r\n\t\t\"friendly_name\": \"近期是否预警预警\"\r\n\t}\r\n}",
      CURLOPT_HTTPHEADER => [
        "Accept: */*",
        "Accept-Encoding: gzip, deflate, br",
        "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJhMDNmMWJjZDg4OTc0MzEwYmIwOWNmY2I1MWRmM2ZiYyIsImlhdCI6MTczNTQ2MDk2OCwiZXhwIjoyMDUwODIwOTY4fQ.KSUcREAdRSVkDf5yUMsnHPKF_ovQS9921A722YYO3VQ",
        "Connection: keep-alive",
        "Content-Type: application/json",
        "User-Agent: PostmanRuntime-ApipostRuntime/1.1.0"
      ],
    ]);

    $response = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }
  }
}
